import { useEffect, useRef, useState } from 'react';

/**
 * EventSource 连接 hook
 */
const useEventSource = (url: string) => {
  const eventSourceRef = useRef<EventSource>(null);

  const [message, setMessage] = useState(null);
  const [error, setError] = useState(null);
  const [readyState, setReadyState] = useState<number>(EventSource.CONNECTING);

  useEffect(() => {
    eventSourceRef.current && eventSourceRef.current.close()
    if (url) {
      eventSourceRef.current = new EventSource(url, { withCredentials: true });

      eventSourceRef.current.onmessage = (event) => {
        console.log("onmessage", event);

        setMessage(event.data)
      };

      eventSourceRef.current.onerror = (event) => {
        console.log("onerror", event);

        setError(event)
        setReadyState(eventSourceRef.current.readyState);
      };

      eventSourceRef.current.onopen = () => {
        setReadyState(eventSourceRef.current.readyState);
      };
    }

    return () => {
      console.log("eventSource close");
      eventSourceRef.current && eventSourceRef.current.close();
    };
  }, [url]);

  const close = () => {
    eventSourceRef.current && eventSourceRef.current.close()
  }
  return { message, error, readyState, close };
};

export default useEventSource;
